package com.ciquan.server.interceptor;

import com.ciquan.server.util.web.MenuUtils;
import com.ciquan.server.util.web.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by kakalee on 15/1/24.
 */
public class LoginInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        if(StringUtils.equals(uri, "/") || StringUtils.equals(uri, "/login") || StringUtils.startsWith(uri, "/api")) {
            return true;
        }

        else if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        else {
            HttpSession session = request.getSession();
            if(session != null && session.getAttribute("user") != null) {
                menus(request);
                return true;
            }
            response.sendRedirect("/");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {

    }

    private void menus(HttpServletRequest request) {
        String uri = request.getRequestURI().substring(1);
        String paths[] = uri.split("/");
        request.setAttribute("menus", MenuUtils.ADMIN_MENUS);
        request.setAttribute("active", MenuUtils.ADMIN_ACTIVE.get(paths[0]));
    }
}
